import { routerRedux } from "dva/router";
import { queryURL } from "utils";
import { login } from "services/login";

export default {
  namespace: "login",
  state: {
    timestamp: new Date().getTime(),
    loginLoading: false
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {});
    }
  },
  effects: {
    *login({ payload }, { put, call, select }) {
      yield put({ type: "showLoginLoading" });
      const data = yield call(login, payload);
      const { locationQuery } = yield select(_ => _.app);
      yield put({ type: "hideLoginLoading" });
      if (data.success) {
        const { expire, token } = data;
        const from = locationQuery;
        sessionStorage.setItem("user", payload.mobile);
        sessionStorage.setItem("expire", expire);
        sessionStorage.setItem("token", token);
        yield put({ type: "app/query" });
        if (from) {
          yield put(routerRedux.push(from));
        } else {
          yield put(routerRedux.push("/dashboard"));
        }
      } else {
        yield put({ type: "reload" });
        throw data;
      }
      yield put({ type: "hideLoginLoading" });
    }
  },
  reducers: {
    reload(state) {
      return {
        ...state,
        timestamp: new Date().getTime()
      };
    },
    showLoginLoading(state) {
      return {
        ...state,
        loginLoading: true
      };
    },
    hideLoginLoading(state) {
      return {
        ...state,
        loginLoading: false
      };
    }
  }
};
